package com.selftool.bo;

import com.selftool.log.Logger;
import com.selftool.main.Intermediary;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.UUID;

/***
 * Dos窗口交互逻辑实现
 */
public class DosBO {
    Intermediary inte = null;
    public DosBO (Intermediary inte){
        this.inte = inte;
    }
    public DosBO (){
    }

    static Runtime rt = Runtime.getRuntime();
    public  void exec(String commands) throws Exception {
        Logger.write("正在执行指令："+commands);
        class MyThread extends Thread {
            @Override
            public void run() {
                try {
                    String uuid = getuuid();
                    //add by CYQ 2024年2月19日 因为linux场景下&&拼接指令无法实现预期效果，故代码控制，将;拆分执行
                    String[] command_strs = commands.split(";");
                    for(int i=0;i<command_strs.length;i++){
                        String command =command_strs[i];
                        Process pr = rt.exec(getOsCmd()+command);
                        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
                        String line = null;
                        while ((line = input.readLine()) != null) {
                            Logger.write("Thread_"+uuid+":"+line);
                        }
                        int exitVal = pr.waitFor();
                        Logger.write("Exited with error code " + exitVal);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("【"+commands+"】指令调用发生异常，"+e.getMessage());
                }
            }
        }
        MyThread newThread = new MyThread();
        newThread.start();
    }
    private String getuuid(){
        UUID randomUUID = UUID.randomUUID();
        return randomUUID.toString().substring(0, 8);
    }

    /***
     * 根据系统属性获取启动命令
     * @return
     */
    private static String getOsCmd(){

        Properties props=System.getProperties(); //获得系统属性集

        String osName = props.getProperty("os.name"); //操作系统名称

        if(osName.toLowerCase().contains("linux")){

            return "/bin/sh -c ";

        }else if(osName.toLowerCase().contains("windows")){

            return "cmd /c ";

        }else{

            throw new RuntimeException("服务器不是linux|windows操作系统");

        }

    }
}
